package jasmine.runner;

import org.junit.Test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static java.lang.System.getProperty;
import static org.junit.Assert.*;

public class JasmineRunnerTest {

    @Test
    public void newRunnerExtractsResourceFilesFromJarToTempDirectory() throws Exception {
        List<File> expectedFiles = expect("jasmine-html.js", "jasmine-webdriver.html", "jasmine.css", "jasmine.js", "buildReport.js");
        assertAllMissing(expectedFiles);

        new JasmineRunner();

        assertAllExist(expectedFiles);
    }

    @Test
    public void weCanRunASingleTest() throws Exception {
        JasmineRunner jasmineRunner = new JasmineRunner("tests/jasmine/javascript", "src/jasmine/javascript");

        jasmineRunner.runJasmineTests("Player.js", "Song.js", "SpecHelper.js", "PlayerSpec.js");
    }

    @Test
    public void testFailsIfADependencyIsMissing() throws Exception {
        JasmineRunner jasmineRunner = new JasmineRunner();
        String dependencyName = "SomeMissingSpec.js";
        try {
            jasmineRunner.runJasmineTests(dependencyName);
            fail("Should have detected a missing dependency");
        } catch (Exception e) {
            assertTrue(e instanceof RuntimeException);
            assertEquals(""
                    + "Could not find dependency [SomeMissingSpec.js] in the provided javascript roots [\n\n"
                    + "] which are relative to your working directory [/Users/chris/Projects/injest]", e.getMessage());
        }
    }

    private void assertAllExist(List<File> files) {
        for (File file : files) {
            if (!file.exists()) fail("File should exist but is missing: " + file);
        }
    }

    private void assertAllMissing(List<File> files) {
        for (File file : files) {
            if (file.exists()) fail("File should be missing but exists: " + file);
        }
    }

    private List<File> expect(String... filenames) {
        ArrayList<File> results = new ArrayList<File>();
        for (String filename : filenames) {
            File file = new File(jasmineTempDir(), filename);
            if (file.exists()) assertTrue("Failed to delete expected file", file.delete());
            results.add(file);
        }
        return results;
    }

    private File jasmineTempDir() {
        return new File(new File(getProperty("java.io.tmpdir")), "jasmine");
    }
}
